package com.mc.jf.apicontroller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mc.jf.entity.HttpListResponse;
import com.mc.jf.entity.HttpResponse;
import com.mc.jf.entity.Member;
import com.mc.jf.entity.ResUtil;
import com.mc.jf.service.impl.MemberServiceImpl;
import com.mc.jf.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.ListUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Lin
 * @since 2022-08-19
 */
@RestController
@RequestMapping("/api/member")
public class MemberApiController {

    @Autowired
    MemberServiceImpl memberService;

    @GetMapping(value = "/child")
    public HttpResponse child(String id) {
        List<Member> memberList = memberService.findMemberByParentId(id);
        return ResUtil.ok(memberList);
    }

    @GetMapping(value = "/parent")
    public HttpResponse parent(String id) {
        Member member = memberService.findParentMember(id);//获取父
        return ResUtil.ok(member);
    }

    @GetMapping(value = "/childByIds")
    public HttpResponse childByIds(String ids) {
        List<Member> memberList = memberService.findMemberByParentIds(ids);//获取父
        return ResUtil.ok(memberList);
    }


    @GetMapping(value = "/detail")
    public HttpResponse detail(String tel) {
        Member member = memberService.getOne(new QueryWrapper<Member>().eq("tel", tel));
        return ResUtil.ok(member);
    }


    @GetMapping(value = "/add")
    public HttpResponse add(String username, String tel, Long p_id) {

        Member member = new Member();
        member.setPId(p_id);
        member.setTel(tel);
        member.setUsername(username);

        if (p_id != null && memberService.getOne(new QueryWrapper<Member>().eq("id", p_id)) == null) {
            return ResUtil.error("推荐人不存在");
        }
        if (memberService.getOne(new QueryWrapper<Member>().eq("tel", tel)) != null) {
            return ResUtil.error("手机号已存在");
        }

        memberService.save(member);

        return ResUtil.ok(member);
    }

    @GetMapping(value = "/list")
    public HttpListResponse list(Long page, Long limit, String searchParams) {


        if (page == null) {
            page = 1L;
        }
        if (limit == null) {
            limit = 10L;
        }


        Page<Member> p = new Page<Member>(page, limit);
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasLength(searchParams)) {
            JSONObject json = JSON.parseObject(searchParams);
            if (json != null) {
                String username = (String) json.get("username");
                String tel = (String) json.get("tel");
                if (StringUtils.hasLength(username)) {
                    queryWrapper.eq("username", username);
                }
                if (StringUtils.hasLength(tel)) {
                    queryWrapper.eq("tel", tel);
                }
            }
        }
        memberService.page(p, queryWrapper);
        List<Member> memberList = p.getRecords();
        return ResUtil.list(p.getTotal(), memberList);
    }

    @GetMapping(value = "/update")
    public HttpResponse update(String username, String tel, Integer score, Long p_id, Long id) {

        if (id == null) {
            return ResUtil.error("用户不存在");
        }
        if (p_id != null && memberService.getOne(new QueryWrapper<Member>().eq("id", p_id)) == null) {
            return ResUtil.error("推荐人不存在");
        }
        Member member = memberService.getOne(new QueryWrapper<Member>().eq("id", id));
        if (member == null) {
            return ResUtil.error("用户不存在");
        }
        if (StringUtils.hasLength(username)) {
            member.setUsername(username);
        }
        if (StringUtils.hasLength(tel)) {
            member.setTel(tel);
        }
        if (score != null) {
            member.setScore(score);
        }
        if (p_id != null) {
            member.setPId(p_id);
        }

        memberService.updateById(member);
        return ResUtil.ok(member);
    }

    @GetMapping(value = "/compute")
    public HttpResponse compute(String tel, Integer score) {
        List<Member> memberList = getScoreList(tel,score);

        if (ListUtils.isEmpty(memberList)){
            return ResUtil.error("未查询到该用户");
        }
        return ResUtil.ok(memberList);
    }

    @GetMapping(value = "/score")
    public HttpResponse score(String tel, Integer score) {
        List<Member> memberList = getScoreList(tel,score);

        if (ListUtils.isEmpty(memberList)){
            return ResUtil.error("未查询到该用户");
        }

        for (int i=0;i<memberList.size();i++){
            memberList.get(i).setScore(memberList.get(i).getScore()+memberList.get(i).getAddScore());
        }
        memberService.updateBatchById(memberList);


        return ResUtil.ok(memberList);
    }

    private List<Member> getScoreList(String tel, Integer score){
        List<Member> memberList = new ArrayList<>();
        Member member = memberService.getOne(new QueryWrapper<Member>().eq("tel", tel));
        Member recommend = null;//一级推荐人
        Member recommend2 = null;
        if (member == null) {
            return memberList;
        }

        if (member.getPId() != null) {
            recommend = memberService.getById(member.getPId());
        }

        if (recommend != null && recommend.getPId() != null) {
            recommend2 = memberService.getById(recommend.getPId());
        }

        if (score==null){
            score=0;
        }
        int scorelevel2=0;
        int scorelevel1=0;
        if (recommend2!=null){
            scorelevel2=(int)(score*Constants.levelp2);
            recommend2.setAddScore(scorelevel2);
            recommend2.setHint("二级推荐人");
        }

        if (recommend!=null){
            scorelevel1=(int)(score*Constants.levelp);
            recommend.setAddScore(scorelevel1);
            recommend.setHint("推荐人");
        }
        score=score-scorelevel1-scorelevel2;
        if (member!=null){
            member.setAddScore(score);
            member.setHint("消费者");
        }

        if (member != null) {
            memberList.add(member);
        }
        if (recommend != null) {
            memberList.add(recommend);
        }
        if (recommend2 != null) {
            memberList.add(recommend2);
        }

        return memberList;
    }
}
